package com.yzh.openai.domain.openai.service.channel.model.impl;

import com.yzh.openai.domain.openai.model.aggregates.ChatProcessAggregate;
import com.yzh.openai.domain.openai.model.entity.MessageEntity;
import com.yzh.openai.domain.openai.service.channel.model.ModelTypeSelector;
import com.yzh.zhipu.model.ImageRequest;
import com.yzh.zhipu.model.ImageResponse;
import com.yzh.zhipu.model.vo.Model;
import com.yzh.zhipu.session.ChatGlmSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Service
public class GlmImageGenerator implements ModelTypeSelector {
    @Resource
    private ChatGlmSession glmSession;

    @Override
    public void doMessageResponse(ChatProcessAggregate chatProcess, ResponseBodyEmitter emitter) {
        // 1.获取用户输入的内容
        MessageEntity messageEntity = chatProcess.getMessages().get(chatProcess.getMessages().size() - 1);

        // 2.封装请求
        ImageRequest imageRequest = new ImageRequest();
        imageRequest.setModel(Model.getEnum(chatProcess.getModel().getCode()));
        imageRequest.setPrompt(messageEntity.getContent());

        try {
            ImageResponse imageResponse = glmSession.genImage(imageRequest);
            String url = imageResponse.getData().get(0).getUrl();

            //直接返回url，前端会判断是否是图片然后展示
            emitter.send(url);

        } catch (Exception e) {
            try {
                emitter.send("系统检测到输入或生成内容可能包含不安全或敏感内容，请您避免输入易产生敏感内容的提示语，感谢您的配合。");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            emitter.complete();
        }
    }
}
